import time
from datetime import datetime
from typing import List

from ch9329.keyboard import Modifier
from ch9329.mouse import MouseCtrl


class Recorder:
    def __init__(self):
        self.start_time = time.time()
        self.writer = None
        # current_time = datetime.now().strftime("%Y%m%d%H%M%S")
        # cmd_file = "./track/" + current_time + ".track"
        # self.writer = open(cmd_file, 'w', encoding='utf-8')

    def start(self):
        if self.writer is None:
            self.start_time = time.time()
            current_time = datetime.now().strftime("%Y%m%d%H%M%S")
            cmd_file = "./track/" + current_time + ".track"
            self.writer = open(cmd_file, 'w', encoding='utf-8')

    def stop(self):
        if self.writer is not None:
            self.writer.close()
            self.writer = None

    def is_started(self):
        return self.writer is not None

    def write_cmd(self, t, c):
        cmd = ('{"delay": ' + self.diff_time() + ', "type": "' + t + '", "cmd": "' + c + '"}')
        print(cmd)
        self.writer.write(cmd + "\n")

    def diff_time(self):
        return str(int((time.time() - self.start_time) * 1000))

    def keyboard_press(self, key: str, modifiers: List[str]):
        self.write_cmd("keyboard", "press('" + key + "'," + str(modifiers) + ")")

    def keyboard_release(self):
        self.write_cmd("keyboard", "release()")

    def mouse_absolute_move(self, x: int, y: int):
        self.write_cmd("mouse", "absolute_move(" + str(x) + ',' + str(y) + ")")

    def mouse_press(self, button: str):
        self.write_cmd("mouse", "press('" + button + "')")

    def mouse_release(self):
        self.write_cmd("mouse", "release()")

    def mouse_wheel(self, wheel: int):
        self.write_cmd("mouse", "wheel(" + str(wheel) + ")")

